package logic

import (
	"context"
	"strings"

	"mall/common/enumx"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShowcaseDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShowcaseDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShowcaseDetailLogic {
	return &ShowcaseDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShowcaseDetailLogic) ShowcaseDetail(in *forum.ShowcaseDetailReq) (*forum.ShowcaseDetailResp, error) {
	if in.Preload == "" && in.EagerLoad == "" {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	if in.Filter == "" {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	logx.Infof("ShowcaseDetailReq: %+v ", in)
	// 

	preloadMap, eagerLoadMap := modelx.GetPreloadMap(in.Preload, in.EagerLoad)
	logx.Infof("preloadMap: %+v ", preloadMap)
	// preloadMap: 
	logx.Infof("eagerLoadMap: %+v ", eagerLoadMap)
	// eagerLoadMap: 

	forumShowcaseEntityName := model.RpcEntityNames.ForumUserShowcase
	_, hasEntitySettings := model.RpcEntityPreloadMap[forumShowcaseEntityName] // ForumUserShowcase的关联字段
	if !hasEntitySettings {
		return &forum.ShowcaseDetailResp{}, nil
	}

	forumShowcaseRepositoryName := model.RepositoryNames.ForumUserShowcase
	columnMap, hasColumnMap := model.RepositoryPreloadMap[forumShowcaseRepositoryName] // ForumUserShowcase的数据库字段
	if !hasColumnMap {
		return &forum.ShowcaseDetailResp{}, nil
	}

	var selectCols []string
	if preloadFields, hasPreloadFields := preloadMap[forumShowcaseEntityName]; hasPreloadFields {
		selectColMap := make(map[string]string)
		for _, field := range preloadFields {
			if _, exist := selectColMap[field]; !exist {
				if column, hasColumn := columnMap[field]; hasColumn {
					selectColMap[field] = column
				} else {
					selectColMap[field] = ""
				}
			}
		}
		for _, column := range selectColMap {
			if column != "" {
				selectCols = append(selectCols, column)
			}
		}
	}

	filterMap := modelx.GetFilterMap(in.Filter, columnMap)
	logx.Infof("filterMap: %+v ", filterMap)
	// filterMap: 

	var pageSize int64 = 1
	showcaseList, _, err := l.svcCtx.ForumUser.GetShowcases(l.ctx, model.M{
		"pageSize": pageSize,
		"select":   strings.Join(selectCols, ","),
	}, -1, filterMap)
	if err != nil {
		return nil, err
	}

	if len(showcaseList) == 0 {
		return &forum.ShowcaseDetailResp{}, nil
	}

	showcase := showcaseList[0]
	sid := showcase.ShowcaseID
	subEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
	if eagerLoadEntities, hasEagerLoadEntities := eagerLoadMap[forumShowcaseEntityName]; hasEagerLoadEntities {
		for _, entity := range eagerLoadEntities {
			if entitySettingMap, hasEntitySettingMap := model.RpcEntityPreloadMap[entity]; hasEntitySettingMap {
				subEntitySettingMap[entity] = entitySettingMap
			}
		}
	}

	var media []*forum.ForumMedia
	forumMediaEntityName := model.RpcEntityNames.ForumMedia
	forumMediaRepositoryName := model.RepositoryNames.ForumMedia
	if _, hasEntitySettingMap := subEntitySettingMap[forumMediaEntityName]; hasEntitySettingMap {
		subPreloadFields, hasSubPreloadFields := preloadMap[forumMediaEntityName]
		subColumnMap, hasSubColumnMap := model.RepositoryPreloadMap[forumMediaRepositoryName]
		if hasSubPreloadFields && hasSubColumnMap {
			selectColMap := make(map[string]string)
			for _, field := range subPreloadFields {
				if _, exist := selectColMap[field]; !exist {
					if column, hasColumn := subColumnMap[field]; hasColumn {
						selectColMap[field] = column
					} else {
						selectColMap[field] = ""
					}
				}
			}
			var subSelectCols []string
			for _, column := range selectColMap {
				if column != "" {
					subSelectCols = append(subSelectCols, column)
				}
			}
			mediaFilterMap := make(map[string]map[string][]interface{})
			mediaFilterMap[model.ForumAttachmentRelationshipColumns.ObjectID] = map[string][]interface{}{
				"equalTo": []interface{}{sid},
			}
			mediaFilterMap[model.ForumAttachmentRelationshipColumns.ObjectType] = map[string][]interface{}{
				"equalTo": []interface{}{enumx.ObjectTypeShowCase},
			}
			mediaList, _, listErr := l.svcCtx.ForumPost.GetMedia(l.ctx, model.M{
				"select": strings.Join(subSelectCols, ","),
			}, -1, mediaFilterMap)
			if listErr != nil {
				return nil, listErr
			}

			if len(mediaList) > 0 {
				for _, item := range mediaList {
					media = append(media, &forum.ForumMedia{
						Uid:       int64(item.AttachmentRelationshipID),
						Id:        int64(item.AttachmentID),
						Uri:       item.AttachmentSource,
						Thumbnail: int32(item.AttachmentThumbnail),
						Order:     int32(item.AttachmentOrder),
						Url:       item.AttachmentImageURL,
						AltText:   item.AttachmentImageAlt,
						Meta:      item.AttachmentImageMeta,
					})
				}
			}
		}
	}

	var desc string
	if showcase.Description.Valid {
		desc = showcase.Description.String
	}

	return &forum.ShowcaseDetailResp{
		Id:         int64(sid),
		UserId:     int64(showcase.UserID),
		PlatformId: int32(showcase.PlatformID),
		Desc:       desc,
		Background: showcase.Background,
		Pattern:    showcase.Pattern,
		Frame:      showcase.Frame,
		CreatedAt:  modelx.FormatTime(showcase.CreatedAt, ""),
		UpdatedAt:  modelx.FormatTime(showcase.UpdatedAt, ""),
		Media:      media,
	}, nil
}
